package com.xms.sdk.api.controller;

import com.xms.schema.entity.Entity;
import com.xms.schema.service.entity.IEntityFinderService;
import com.xms.sdk.api.model.DeleteEntityRecordModel;
import com.xms.sdk.service.IDataDeleter;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

/**
 * <p>
 * DataDeleterController
 * </p>
 *
 * @author migo
 * @since 2021/9/16
 */
@RestController
@RequestMapping("{org}/api/data/delete")
public class DataDeleterController extends ApiBaseController {
    private IEntityFinderService _entityFinderService;
    private IDataDeleter _dataDeleter;

    public DataDeleterController(IEntityFinderService entityFinderService
            , IDataDeleter dataDeleter)
    {
        _entityFinderService = entityFinderService;
        _dataDeleter = dataDeleter;
    }

    @ApiOperation("删除记录")
    @PostMapping()
    public JsonResultObject delete(@RequestBody DeleteEntityRecordModel model) throws Exception {
        if (CollectionUtil.isEmpty(model.RecordId))
        {
            return JNotSpecifiedRecord();
        }
        Entity entityMetadata = null;
        if (StringUtil.notEmpty(model.EntityName))
        {
            entityMetadata = _entityFinderService.getByName(model.EntityName);
        }
        else
        {
            entityMetadata = _entityFinderService.getById(model.EntityId);
        }
        if (entityMetadata == null)
        {
            return JNotFound();
        }
        _dataDeleter.delete(entityMetadata.getName(), Arrays.asList(model.RecordId));
        return JDeleteSuccess();
    }
}
